package com.bestom.smartwatch.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanSettings;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;

import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.bestom.smartwatch.R;
import com.bestom.smartwatch.SmartWatchApplication;
import com.bestom.smartwatch.adapter.AutoPollAdapter;
import com.bestom.smartwatch.adapter.IconAdapter;
import com.bestom.smartwatch.bean.IconBean;
import com.bestom.smartwatch.manage.SQLiteManage;
import com.bestom.smartwatch.manage.ScrollSpeedLinearLayoutManger;
import com.bestom.smartwatch.service.SampleBleService;
import com.bestom.smartwatch.util.ConversionUtil;
import com.bestom.smartwatch.util.ExcelUtil;
import com.bestom.smartwatch.util.ToastUtil;
import com.bestom.smartwatch.util.WeiboDialogUtils;
import com.sxr.sdk.ble.keepfit.aidl.IRemoteService;
import com.sxr.sdk.ble.keepfit.aidl.IServiceCallback;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;

import static com.bestom.smartwatch.SmartWatchApplication.CLASS_NAME;
import static com.bestom.smartwatch.SmartWatchApplication.SCHOOL_NAME;
import static com.bestom.smartwatch.util.LogUtil.log;

@RequiresApi(api = Build.VERSION_CODES.O)
public class MainActivity extends com.bestom.smartwatch.activity.BaseActivity {

    private static final String TAG = "MainActivity";
    @BindView(R.id.students_manage)
    TextView studentsManage;
    @BindView(R.id.student_id)
    TextView studentsId;
    @BindView(R.id.start_collection)
    TextView startCollection;
    @BindView(R.id.again_collection)
    TextView againCollection;
    @BindView(R.id.student_name)
    TextView studentsName;
    @BindView(R.id.max_temp)
    TextView maxTempV;
    @BindView(R.id.body_temp)
    TextView bodyTempV;
    @BindView(R.id.surface_temp)
    TextView surfaceTempV;
    @BindView(R.id.heart_rate)
    TextView heartRate;
    @BindView(R.id.blood_pressure)
    TextView bloodPressure;
    @BindView(R.id.diastolic_blood_pressure)
    TextView diastolicBloodPressure;
    @BindView(R.id.blood_oxygen)
    TextView bloodOxygen;
    @BindView(R.id.step)
    TextView stepV;
    @BindView(R.id.calorie)
    TextView calorieV;
    @BindView(R.id.kilometre)
    TextView kilometreV;
    @BindView(R.id.message)
    TextView message;
    @BindView(R.id.school_name)
    TextView schoolName;
    @BindView(R.id.class_number)
    TextView classNumber;
    @BindView(R.id.service_status)
    TextView serviceStatus;
    @BindView(R.id.now_connect)
    TextView nowConnect;
    @BindView(R.id.class_name)
    TextView className;
    @BindView((R.id.autoPoll_recyclerView))
    RecyclerView recyclerView;
    @BindView((R.id.main_root))
    ConstraintLayout mainRoot;
    @BindView((R.id.info_linearLayout))
    LinearLayout infoLinearLayout;
    @BindView((R.id.right_linearLayout))
    LinearLayout rightLinearLayout;
    @BindView((R.id.left_down_linearLayout))
    LinearLayout leftDownLinearLayout;
    @BindView(R.id.line1)
    TextView line1;
    @BindView(R.id.line2)
    TextView line2;
    @BindView(R.id.line3)
    TextView line3;
    @BindView(R.id.line4)
    TextView line4;
    @BindView(R.id.line5)
    TextView line5;

    private Context mContext;
    private AlertDialog alertDialog1 = null;
    private AlertDialog alertDialog = null;
    private SQLiteManage mSQLiteManage;
    private int width;
    private int height;
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mContext = this;
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        // 确认权限
        checkPermissions();

        Window window = getWindow();
        DisplayMetrics metric = new DisplayMetrics();
        window.getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 初始化展示数据
        initShowData();
        // 屏幕宽度（像素）
        width = metric.widthPixels;
        // 屏幕高度（像素）
        height = metric.heightPixels;
        runOnUiThread(() -> classNumber.setText(String.valueOf(mSQLiteManage.selectAll().getCount())));
        // 绑定服务
        Intent intent = new Intent(IRemoteService.class.getName());
        intent.setClassName("com.sxr.sdk.ble.keepfit.client", "com.sxr.sdk.ble.keepfit.client.SampleBleService");
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }

    private void initShowData() {
        Executors.newSingleThreadExecutor().execute(() -> {
            Cursor cursor = mSQLiteManage.selectLastNumberData(10);
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    HashMap<String, String> map = new HashMap<>();
                    String studentName = cursor.getString(cursor.getColumnIndex("students_name"));
                    String itemStep = cursor.getString(cursor.getColumnIndex("students_step"));
                    String bodyTemp = cursor.getString(cursor.getColumnIndex("students_body_temp"));
                    String measureTime = cursor.getString(cursor.getColumnIndex("students_time"));
                    map.put("itemName", studentName);
                    map.put("itemStep", itemStep);
                    map.put("itemTemp", bodyTemp);
                    map.put("itemTime", measureTime.split(" ")[1]);
                    listBeans.add(map);
                }
                cursor.close();
            }
            mAutoPollAdapter.notifyDataSetChanged();
        });
    }

    private ScrollSpeedLinearLayoutManger mScrollSpeedLinearLayoutManger;
    private IRemoteService mService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            mService = IRemoteService.Stub.asInterface(service);
            try {
                mService.registerCallback(mIServiceCallback);
                mService.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);

                if (mService.isAuthrize() == 200) {
                        serviceStatus.setText("在线");
                        serviceStatus.setTextColor(Color.GREEN);
                } else {
                        serviceStatus.setText("不在线");
                        serviceStatus.setTextColor(Color.RED);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            runOnUiThread(() -> {
                serviceStatus.setText("不在线");
                serviceStatus.setTextColor(Color.RED);
            });
            mService = null;
        }
    };
    private PopupWindow window;
    private EditText fileNameEditText;

    @Override
    protected void initView() {
        fileNameEditText = new EditText(this);
        fileNameEditText.setTextColor(Color.BLACK);
        schoolName.setText((String) SmartWatchApplication.getApplication().settingsGet(SCHOOL_NAME, ""));
        className.setText((String) SmartWatchApplication.getApplication().settingsGet(CLASS_NAME, ""));
        runOnUiThread(()->{
            mainRoot.setBackgroundResource(R.drawable.background);
            infoLinearLayout.setBackgroundResource(R.drawable.left_top_background);
            leftDownLinearLayout.setBackgroundResource(R.drawable.left_down_background);
            rightLinearLayout.setBackgroundResource(R.drawable.right_background);
            line1.setBackgroundResource(R.drawable.line);
            line2.setBackgroundResource(R.drawable.line);
            line3.setBackgroundResource(R.drawable.line);
            line4.setBackgroundResource(R.drawable.line);
            line5.setBackgroundResource(R.drawable.line);
//            startCollection.setBackgroundResource(R.drawable.ripple_bg);
//            againCollection.setBackgroundResource(R.drawable.ripple_bg);
            startCollection.setOnClickListener(v -> {
                startCollection.setText("重新采集");
                againCollection.setVisibility(View.VISIBLE);
                bleArrayList.clear();
                bleNameArrayList.clear();
                flag = true;
                studentsName.setText("");
                studentsId.setText("");
                ok = true;
                stop = true;
                num = 0;
                scanDevice();
            });
            againCollection.setOnClickListener(v -> {
                String string = againCollection.getText().toString();
                if (string.equals("继续采集")){
                    againCollection.setText("停止采集");
                    mScanBleHandler.postDelayed(() -> {
                        stopCollection = true;
                        if (bodyTempV.getText().toString().equals("失败")){
                            Message message = new Message();
                            message.what = 999;
                            message.obj = bleArrayList.get(num);
                            mScanBleHandler.sendMessage(message);
                        }
                    },2000);
                    scanDevice();
                    size = bleArrayList.size();
                    if (isSave) {
                        studentsId.setText("");
                        studentsName.setText("");
                    }
                }else {
                    stopCollection = false;
                    againCollection.setText("继续采集");
                    mScanBleHandler.postDelayed(() -> {
                        if (bodyTempV.getText().toString().equals("采集中...")) bodyTempV.setText("失败");
                    },2000);
                }
            });
//            studentsManage.setBackgroundResource(R.drawable.ripple_bg);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        mScanBleHandler.post(() -> {
            LayoutInflater lay = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popView = lay.inflate(R.layout.popwindow, null);
            runOnUiThread(() -> {
                popView.findViewById(R.id.pop_root).setBackgroundResource(R.drawable.background);
                popView.findViewById(R.id.center_linearLayout).setBackgroundResource(R.drawable.pop_background);
                popView.findViewById(R.id.line1_tv).setBackgroundResource(R.drawable.pop_line);
                popView.findViewById(R.id.line2_tv).setBackgroundResource(R.drawable.pop_line);
                popView.findViewById(R.id.line3_tv).setBackgroundResource(R.drawable.pop_line);
                popView.findViewById(R.id.line4_tv).setBackgroundResource(R.drawable.pop_line);
            /*popView.findViewById(R.id.select).setBackgroundResource(R.drawable.ripple_bg);
            popView.findViewById(R.id.modification).setBackgroundResource(R.drawable.ripple_bg);
            popView.findViewById(R.id.save).setBackgroundResource(R.drawable.ripple_bg);
            popView.findViewById(R.id.saveSchoolClass).setBackgroundResource(R.drawable.ripple_bg);
            popView.findViewById(R.id.pull).setBackgroundResource(R.drawable.ripple_bg);
            popView.findViewById(R.id.cancel).setBackgroundResource(R.drawable.ripple_bg);
            popView.findViewById(R.id.select_id).setBackgroundResource(R.drawable.ripple_bg);*/
                studentsManage.setOnClickListener(v -> popWindow(v, popView));
            });
        });

    }

    private String selectName = null;
    private String selectTime = null;
    private List<IconBean> mIconBeenList;
    private IconAdapter iconAdapter;
    private ArrayAdapter<String> selectIdAdapter;
    public void popWindow(View parent, View popView) {

        if (window == null) {
            mIconBeenList = new ArrayList<>();
            Spinner nameSpinner = popView.findViewById(R.id.name_spinner);
            Spinner idSpinner = popView.findViewById(R.id.id_spinner);
            TextView idTextView = popView.findViewById(R.id.id_text_view);
            TextView nameTextView = popView.findViewById(R.id.name_text_view);
            TextView mTimeTextView = popView.findViewById(R.id.time_TextView);
            TextView select = popView.findViewById(R.id.select);
            TextView selectId = popView.findViewById(R.id.select_id);
            ListView selectListView = popView.findViewById(R.id.select_listView);
            iconAdapter = new IconAdapter(mContext, mIconBeenList);
            selectListView.setAdapter(iconAdapter);
            ImageView back = popView.findViewById(R.id.back);
            TextView modification = popView.findViewById(R.id.modification);
            TextView save = popView.findViewById(R.id.save);
            TextView saveSchoolClass = popView.findViewById(R.id.saveSchoolClass);
            TextView pull = popView.findViewById(R.id.pull);
            TextView cancel = popView.findViewById(R.id.cancel);
            TextView deviceId = popView.findViewById(R.id.device_id);
            EditText popStudentName = popView.findViewById(R.id.pop_student_name);
            EditText popStudentId = popView.findViewById(R.id.pop_student_id);
            EditText popSchoolName = popView.findViewById(R.id.pop_school_name);
            EditText popClassName = popView.findViewById(R.id.pop_class_name);

            window = new PopupWindow(popView, width, height, true);
            window.setOutsideTouchable(true);
            window.setFocusable(true);
            window.update();
            window.showAtLocation(parent, Gravity.CENTER_VERTICAL, 0, 0);
            window.setOnDismissListener(() -> {
                selectName = null;
                selectTime = null;
                mIconBeenList = null;
                iconAdapter = null;
                window = null;
                alertDialog1 = null;
                alertDialog = null;
            });
            runOnUiThread(() -> {
                popStudentName.setEnabled(false);
                popStudentId.setEnabled(false);
                popSchoolName.setEnabled(false);
                popClassName.setEnabled(false);
                deviceId.setText(nowDeviceId);
                popSchoolName.setText(schoolName.getText().toString());
                popClassName.setText(className.getText().toString());
            });


            Cursor cursorAll = mSQLiteManage.selectAll();
            ArrayList<String> mItemArrayList = new ArrayList<>();
            mItemArrayList.add("全部");
            if (cursorAll.getCount() > 0) {
                while (cursorAll.moveToNext()) {
                    String name = cursorAll.getString(cursorAll.getColumnIndex("students_name"));
                    mItemArrayList.add(name);
                }
                cursorAll.close();
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.spinner_item, mItemArrayList);

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            //绑定 Adapter到控件
            nameSpinner.setAdapter(adapter);

            final int[] checkedItem1 = {0};
            nameTextView.setOnClickListener(v -> {
                String[] items = new String[mItemArrayList.size()];
                items = mItemArrayList.toArray(items);
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.setTitle("请选择姓名");
                alertBuilder.setSingleChoiceItems(items, checkedItem1[0], (dialogInterface, i) -> {
                    checkedItem1[0] = i;
                    nameSpinner.setSelection(i);
                    selectName = mItemArrayList.get(i);
                    if (selectName.equals("全部")) selectName = null;
                    alertDialog1.dismiss();
                });

                alertDialog1 = alertBuilder.create();
                alertDialog1.show();

            });

            /*nameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view,
                                           int pos, long id) {
                    selectName = mItemArrayList.get(pos);
                    if (selectName.equals("全部")) selectName = null;
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // Another interface callback
                }
            });*/

            idSpinner.setAdapter(selectIdAdapter);
            final int[] checkedItem = {0};
            idTextView.setOnClickListener(v -> {
                if (update){
                    ToastUtil.toast("更新中，请稍后...");
                    return;
                }
                String[] items = new String[bleNameArrayList.size()];
                items = bleNameArrayList.toArray(items);
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mContext);
                alertBuilder.setTitle("请选择设备Id");
                alertBuilder.setSingleChoiceItems(items, checkedItem[0], (dialogInterface, i) -> {
                    checkedItem[0] = i;
                    idSpinner.setSelection(i);
                    Cursor cursor = mSQLiteManage.select(bleNameArrayList.get(i));

                    if (cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {
                            popStudentName.setText(cursor.getString(cursor.getColumnIndex("students_name")));
                            popStudentId.setText(cursor.getString(cursor.getColumnIndex("students_id")));
                        }
                    }else {
                        popStudentName.setText("");
                        popStudentId.setText("");
                    }
                    cursor.close();
                    alertDialog.dismiss();
                });

                alertDialog = alertBuilder.create();
                alertDialog.show();

            });

            /*idSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    String deviceId = (String) idSpinner.getSelectedItem();
                    Cursor cursor = mSQLiteManage.select(deviceId);

                    if (cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {
                            popStudentName.setText(cursor.getString(cursor.getColumnIndex("students_name")));
                            popStudentId.setText(cursor.getString(cursor.getColumnIndex("students_id")));
                        }
                    }else {
                        popStudentName.setText("");
                        popStudentId.setText("");
                    }
                    cursor.close();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });*/
            mTimeTextView.setOnClickListener(v -> {
//                String[] timeS = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).split("-");
                Date date = new Date(System.currentTimeMillis());
                String[] timeS = simpleDateFormat.format(date).split(" ")[0].split("-");
                selectTime = null;
                mTimeTextView.setText("所有日期");

                //通过自定义控件AlertDialog实现
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                View view = (LinearLayout) getLayoutInflater().inflate(R.layout.date_dialog, null);
                final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
                //设置日期简略显示 否则详细显示 包括:星期\周
                datePicker.setCalendarViewShown(false);
                //初始化当前日期
                datePicker.init(Integer.parseInt(timeS[0]), Integer.parseInt(timeS[1]), Integer.parseInt(timeS[2]), null);
                //设置date布局
                builder.setView(view);
                builder.setTitle("设置日期信息");
                builder.setPositiveButton("确  定", (dialog, which) -> {
                    //日期格式
                    selectTime = datePicker.getYear() + "-" + datePicker.getMonth() + "-" + datePicker.getDayOfMonth();
                    mTimeTextView.setText(selectTime);
                    dialog.cancel();
                });
                builder.setNegativeButton("取  消", (dialog, which) -> dialog.cancel());
                builder.create().show();

            });
            select.setOnClickListener(v -> selectToShow(selectName, selectTime));
            selectId.setOnClickListener(v -> {
                if (update) {
                    ToastUtil.toast("更新中，请稍等...");
                    return;
                }
                bleNameArrayList.clear();
                update = true;
                scanDevice();
            });
            back.setOnClickListener(v -> {
                runOnUiThread(() -> {
                    update = false;
                    schoolName.setText(popSchoolName.getText().toString().trim());
                    className.setText(popClassName.getText().toString().trim());
                    classNumber.setText(String.valueOf(mSQLiteManage.selectAll().getCount()));
                });
                window.dismiss();
            });

            pull.setOnClickListener(v -> {
                int margin = dpToPx(20);
                fileNameEditText.setEnabled(true);
                if (fileNameEditText.getParent() != null)
                    ((ViewGroup) fileNameEditText.getParent()).removeView(fileNameEditText);
                new AlertDialog.Builder(mContext)
                        .setTitle("请输入文件名")
                        .setView(fileNameEditText, margin, 0, margin, 0)
                        .setMessage("您将要导出" + nameSpinner.getSelectedItem() + "," + mTimeTextView.getText() + " 的数据到 " + filePath + "?")
                        .setNegativeButton("取消", (dialog, which) -> {
                                    fileNameEditText.setEnabled(false);
                                    dialog.dismiss();
                        })
                        .setPositiveButton("确定", (dialog, which) -> {
                            fileNameEditText.setEnabled(false);
                            String fileName = fileNameEditText.getText().toString().trim();
                            if (fileName.isEmpty()) {
                                ToastUtil.toast("文件名不能为空！");
                            } else {
                                fileName = "/" + fileName + ".xls";
                                if (new File(filePath + fileName).exists()) {
                                    ToastUtil.toast("改文件名已存在，请重新输入！");
                                } else {
                                    List<IconBean> mList = new ArrayList<>();

                                    String[] title = {"姓名", "最高温度", "身体温度", "体表温度", "步数", "卡路里", "公里数", "心率", "血氧", "记录时间"};
                                    ExcelUtil.initExcel(filePath, fileName, title);
                                    Cursor cursor1 = mSQLiteManage.selectStudentAllDataByNameAndTime(selectName, selectTime);
                                    if (cursor1.getCount() > 0) {
                                        Dialog loadingDialog = WeiboDialogUtils.createLoadingDialog(mContext, "正在导出...");//开启加载动画
                                        while (cursor1.moveToNext()) {
                                            IconBean mIconBean = new IconBean(
                                                    cursor1.getString(cursor1.getColumnIndex("students_name")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_max_temp")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_body_temp")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_skin_temp")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_step")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_calories")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_distance")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_heart_rate")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_blood_oxygen")),
                                                    cursor1.getString(cursor1.getColumnIndex("students_time")));
                                            mList.add(mIconBean);
                                        }
                                        cursor1.close();
                                        ExcelUtil.writeObjListToExcel(mList, filePath + fileName);
                                        WeiboDialogUtils.closeDialog(loadingDialog);//关闭动画
                                        ToastUtil.toast("导出成功");
                                    } else {
                                        ToastUtil.toast("未查询到数据！");
                                    }
                                }
                            }
                        })
                        .show();
            });

            cancel.setOnClickListener(v -> {
                popStudentName.setEnabled(false);
                popStudentId.setEnabled(false);
                popSchoolName.setEnabled(false);
                popClassName.setEnabled(false);
            });
            save.setOnClickListener(v -> {
                String name = popStudentName.getText().toString().trim();
                Object selectedItem = idSpinner.getSelectedItem();
                if (selectedItem == null){
                    ToastUtil.toast("请先选择设备Id");
                    return;
                }

                if (name.isEmpty()) {
                    ToastUtil.toast("姓名不能为空");
                    return;
                }
                int result = saveStudentInfo(idSpinner.getSelectedItem().toString(), name, popStudentId.getText().toString().trim(), popClassName.getText().toString().trim());
                popStudentName.setEnabled(false);
                popStudentId.setEnabled(false);
                popSchoolName.setEnabled(false);
                popClassName.setEnabled(false);
                if (result == -1) ToastUtil.toast("该姓名已存在，请重新输入以区别");
                else if (result == 1) ToastUtil.toast("添加成功");
                else {
                    ToastUtil.toast("修改成功");
                    if (!studentNameInPop.isEmpty() && !name.equals(studentNameInPop)) {
                        mItemArrayList.remove(studentNameInPop);
                        mItemArrayList.add(name);
                        adapter.notifyDataSetChanged();
                    }
                }

            });

            saveSchoolClass.setOnClickListener(v -> {
                popStudentName.setEnabled(false);
                popStudentId.setEnabled(false);
                popSchoolName.setEnabled(false);
                popClassName.setEnabled(false);
                SmartWatchApplication.getApplication().settingsPut(SCHOOL_NAME, popSchoolName.getText().toString().trim());
                SmartWatchApplication.getApplication().settingsPut(CLASS_NAME, popClassName.getText().toString().trim());
                ToastUtil.toast("保存成功");
            });
            modification.setOnClickListener(v -> {
                studentNameInPop = popStudentName.getText().toString().trim();
                popStudentName.setEnabled(true);
                popStudentId.setEnabled(true);
                popSchoolName.setEnabled(true);
                popClassName.setEnabled(true);

            });
        }
    }
    private String studentNameInPop = "";
    private void selectToShow(String selectName, String selectTime) {

        Cursor cursor = mSQLiteManage.selectStudentAllDataByNameAndTime(selectName, selectTime);
        mIconBeenList.clear();
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                IconBean mIconBean = new IconBean(
                        cursor.getString(cursor.getColumnIndex("students_name")),
                        cursor.getString(cursor.getColumnIndex("students_max_temp")),
                        cursor.getString(cursor.getColumnIndex("students_body_temp")),
                        cursor.getString(cursor.getColumnIndex("students_skin_temp")),
                        cursor.getString(cursor.getColumnIndex("students_step")),
                        cursor.getString(cursor.getColumnIndex("students_calories")),
                        cursor.getString(cursor.getColumnIndex("students_distance")),
                        cursor.getString(cursor.getColumnIndex("students_heart_rate")),
//                        cursor.getString(cursor.getColumnIndex("students_systolic_blood_pressure")),
//                        cursor.getString(cursor.getColumnIndex("students_diastolic_blood_pressure")),
                        cursor.getString(cursor.getColumnIndex("students_blood_oxygen")),
                        cursor.getString(cursor.getColumnIndex("students_time")));
                mIconBeenList.add(mIconBean);
            }
            cursor.close();
        } else {
            ToastUtil.toast("未查询到数据！");
        }
        iconAdapter.notifyDataSetChanged();
    }

    /**
     * 弹出框设置编辑文本左右距离
     */
    private int dpToPx(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }

    private int saveStudentInfo(String deviceId, String popStudentName, String popStudentId, String popStudentClass) {
        if (mSQLiteManage.exist(deviceId))
            return mSQLiteManage.update(deviceId, popStudentName, popStudentId, popStudentClass);
        else return mSQLiteManage.add(deviceId, popStudentName, popStudentId, popStudentClass);

    }

    private AutoPollAdapter mAutoPollAdapter;
    private ArrayList<HashMap<String, String>> listBeans;
    private String filePath = "";
    private SimpleDateFormat simpleDateFormat;
    @Override
    protected void initData() {
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bleArrayList = new ArrayList<>();
        bleNameArrayList = new ArrayList<>();
        filePath = Environment.getExternalStorageDirectory() + "/AndroidExcel";
        /*String path = getSDPath();
        if (path != null){
            log("getSDPath","the sdcard path--->" + path);
            filePath = "storage/" + path+ "/AndroidExcel";
        }*/
        File file = new File(filePath);
        if (!file.exists()) file.mkdirs();
        mSQLiteManage = new SQLiteManage(mContext);
        recyclerView.setHasFixedSize(true);
        mScrollSpeedLinearLayoutManger = new ScrollSpeedLinearLayoutManger(mContext);
        recyclerView.setLayoutManager(mScrollSpeedLinearLayoutManger);
        listBeans = new ArrayList<>();
        mAutoPollAdapter = new AutoPollAdapter(mContext, listBeans);
        recyclerView.setAdapter(mAutoPollAdapter);
        selectIdAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, bleNameArrayList);
        selectIdAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }

    private String getSDPath(){
        StorageManager mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        List<StorageVolume> storageVolumes = mStorageManager.getStorageVolumes();

        if (storageVolumes.size() >= 2){
            return storageVolumes.get(1).getUuid();
        }

        return null;
    }

    private void checkPermissions() {
        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(getApplicationContext(), permission) != PackageManager.PERMISSION_GRANTED)
                    ActivityCompat.requestPermissions(this, permissions, 123);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 123) {
            boolean isAllGranted = true;
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    isAllGranted = false;
                    break;
                }
            }
            //如果没有获取权限，那么可以提示用户去设置界面--->应用权限开启权限
            if (!isAllGranted) ToastUtil.toast("请前往设置界面授予权限");

        }
    }

    /**
     * 检查权限
     */
    private boolean isAdapterEnabled() {
        return BluetoothAdapter.getDefaultAdapter().isEnabled();
    }
    /**
     * 开始扫描 10秒后自动停止
     * */
    private Runnable scannable;
    private Handler handler = new Handler();
    private void scanDevice() {
        if (isAdapterEnabled()) {
            ToastUtil.toast("开始采集中，请稍后...");
            if (mService != null) {
                try {
                    mService.scanDevice(true);
                } catch (RemoteException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Remote call error!", Toast.LENGTH_SHORT).show();
                }
                scannable = this::stopScanDevice;
                handler.postDelayed(scannable, 15000);
            } else {
                Toast.makeText(getApplicationContext(), "Service is not available yet!", Toast.LENGTH_SHORT).show();
            }
        } else {
            update = false;
            startCollection.setText("开始采集");
            againCollection.setVisibility(View.GONE);
            ToastUtil.toast("请先前往设置打开蓝牙，再进行此操作");
        }

    }
    /**
     * 停止扫描
     * */
    private void stopScanDevice(){
        if (scannable != null){
            handler.removeCallbacks(scannable);
            scannable = null;
        }
        try {
            mService.scanDevice(false);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if (bleArrayList.size() == 0 || size == bleArrayList.size()){
            startCollection.setText("重新采集");
            againCollection.setText("继续采集");
        }
        update = false;
        mScanBleHandler.sendEmptyMessage(123);
    }
    private ScheduledExecutorService executorScanBleService;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (mService != null && mService.isConnectBt()) mService.disconnectBt(true);
            mService = null;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mScanBleHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

//            if (msg.what == 123) scanDevice();
            if (msg.what == 999){
                num += 1;
                String[] split = msg.obj.toString().split("&&");
                Cursor cursor = mSQLiteManage.select(split[0]);
                if (cursor.getCount() > 0) {
                    if (cursor.moveToFirst()) {
                        runOnUiThread(() -> {
                            studentsName.setText(cursor.getString(cursor.getColumnIndex("students_name")));
                            studentsId.setText(cursor.getString(cursor.getColumnIndex("students_id")));
                            maxTempV.setText("采集中...");
                            bodyTempV.setText("采集中...");
                            surfaceTempV.setText("采集中...");
                            heartRate.setText("采集中...");
                            bloodOxygen.setText("采集中...");
                            bloodPressure.setText("采集中...");
                            diastolicBloodPressure.setText("采集中...");
                            stepV.setText("采集中...");
                            kilometreV.setText("采集中...");
                            calorieV.setText("采集中...");
                            nowConnect.setText(split[0]);
                            cursor.close();
                        });
                        try {
                            if (mService.isConnectBt()) mService.disconnectBt(true);
                            mService.connectBt(split[0],split[1]);
                            ok = true;
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }else cursor.close();
            } else if (msg.what == 456) mAutoPollAdapter.notifyDataSetChanged();
            else if (msg.what == 123) selectIdAdapter.notifyDataSetChanged();
            else if (msg.what == 770) {
                ToastUtil.toast("采集完成，存在未采集学生，请检查");
                againCollection.setText("继续采集");
            }
            else if (msg.what == 771) {
                ToastUtil.toast("所有学生均已采集完成。");
                startCollection.setText("开始采集");
                againCollection.setText("停止采集");
                againCollection.setVisibility(View.GONE);
            }
        }
    };

    private int oldRssi = -85;
    private String nowDeviceId = "";
    private String nowMaxTemp = "";
    private String nowBodyTemp = "";
    private String nowSkinTemp = "";
    private String nowStep = "";
    private String nowCalories = "";
    private String nowDistance = "";
    private String nowHeartRate = "";
    private String nowSystolicBloodPressure = "";
    private String nowDiastolicBloodPressure = "";
    private String nowBloodOxygen = "";
    private ArrayList<String> bleArrayList;
    private ArrayList<String> bleNameArrayList;
    private static boolean flag = true;
    private static boolean ok = true;
    private static boolean isSave = false;
    private static boolean stopCollection = true;
    private static boolean stop = false;
    private static boolean update = false;
    private static int num = 0;
    private static int size = 0;
    private IServiceCallback mIServiceCallback = new IServiceCallback.Stub() {

        @Override
        public void onConnectStateChanged(int state) throws RemoteException {
            log("onConnectStateChanged", " state " + state);
            if (state == 2) {
                mService.getCurSportData();
//                mService.setHeartRateMode(true, 30);
//                mService.setBloodPressureMode(true);
                mService.setTemperatureMode(true);
            }
        }

        @Override
        public void onScanCallback(final String deviceName, final String deviceMacAddress, final int rssi)
                throws RemoteException {
            if (deviceName != null && (deviceName.startsWith("F29") || deviceName.startsWith("WS-"))) {
                String bleString = deviceName + "&&" + deviceMacAddress;
                if (!bleNameArrayList.contains(deviceName)) bleNameArrayList.add(deviceName);
                if (!bleArrayList.contains(bleString) && !update) {
                    bleArrayList.add(bleString);
                    if (flag || stop){
                        flag = false;
                        stop = false;
                        Message message = new Message();
                        message.what = 999;
                        message.obj = bleArrayList.get(num);
                        mScanBleHandler.postDelayed(() -> mScanBleHandler.sendMessage(message),3000);
                    }
                }
            }
        }

        @Override
        public void onSetNotify(int result) throws RemoteException {
            log("onSetNotify", String.valueOf(result));
        }

        @Override
        public void onSetUserInfo(int result) throws RemoteException {
            log("onSetUserInfo", "" + result);
        }

        @Override
        public void onAuthSdkResult(int errorCode) throws RemoteException {
            log("onAuthSdkResult", errorCode + "");
        }

        @Override
        public void onGetDeviceTime(int result, String time) throws RemoteException {
            log("onGetDeviceTime", String.valueOf(time));
        }

        @Override
        public void onSetDeviceTime(int arg0) throws RemoteException {
            log("onSetDeviceTime", arg0 + "");
        }

        @Override
        public void onSetDeviceInfo(int arg0) throws RemoteException {
            log("onSetDeviceInfo", arg0 + "");
        }


        @Override
        public void onAuthDeviceResult(int arg0) throws RemoteException {
            log("onAuthDeviceResult", arg0 + "");
        }


        @Override
        public void onSetAlarm(int arg0) throws RemoteException {
            log("onSetAlarm", arg0 + "");
        }

        @Override
        public void onSendVibrationSignal(int arg0) throws RemoteException {
            log("onSendVibrationSignal", "result:" + arg0);
        }

        @Override
        public void onGetDeviceBatery(int arg0, int arg1)
                throws RemoteException {
            log("onGetDeviceBatery", "batery:" + arg0 + ", statu " + arg1);
        }


        @Override
        public void onSetDeviceMode(int arg0) throws RemoteException {
            log("onSetDeviceMode", "result:" + arg0);
        }

        @Override
        public void onSetHourFormat(int arg0) throws RemoteException {
            log("onSetHourFormat ", "result:" + arg0);

        }

        @Override
        public void setAutoHeartMode(int arg0) throws RemoteException {
            log("setAutoHeartMode ", "result:" + arg0);
        }


        @Override
        public void onGetCurSportData(int type, long timestamp, int step, int distance,
                                      int cal, int cursleeptime, int totalrunningtime, int steptime) throws RemoteException {
            Date date = new Date(timestamp * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String time = sdf.format(date);
            log("onGetCurSportData", "type : " + type + " , time :" + time + " , step: " + step + ", distance :" + distance + ", cal :" + cal + ", cursleeptime :" + cursleeptime + ", totalrunningtime:" + totalrunningtime);
            runOnUiThread(() -> {
                nowStep = String.valueOf(step);
                nowDistance = String.valueOf(distance);
                nowCalories = String.valueOf(cal);
                stepV.setText(nowStep);
                kilometreV.setText(nowDistance);
                calorieV.setText(nowCalories);
            });
        }

        @Override
        public void onGetSenserData(int result, long timestamp, int heartrate, int sleepstatu)
                throws RemoteException {
            Date date = new Date(timestamp * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String time = sdf.format(date);
            log("onGetSenserData", "result: " + result + ",time:" + time + ",heartrate:" + heartrate + ",sleepstatu:" + sleepstatu);

        }


        @Override
        public void onGetDataByDay(int type, long timestamp, int step, int heartrate)
                throws RemoteException {
            Date date = new Date(timestamp * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String recorddate = sdf.format(date);
            log("onGetDataByDay", "type:" + type + ",time::" + recorddate + ",step:" + step + ",heartrate:" + heartrate);

        }

        @Override
        public void onGetDataByDayEnd(int type, long timestamp) throws RemoteException {
            Date date = new Date(timestamp * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String recorddate = sdf.format(date);
            log("onGetDataByDayEnd", type + " time:" + recorddate);

        }


        @Override
        public void onSetPhontMode(int arg0) throws RemoteException {
            log("onSetPhontMode", "result:" + arg0);
        }


        @Override
        public void onSetSleepTime(int arg0) throws RemoteException {
            log("onSetSleepTime", "result:" + arg0);
        }


        @Override
        public void onSetIdleTime(int arg0) throws RemoteException {
            log("onSetIdleTime", "result:" + arg0);
        }


        @Override
        public void onGetDeviceInfo(int version, String macaddress, String vendorCode,
                                    String productCode, int result) throws RemoteException {
            log("onGetDeviceInfo", "version :" + version + ",macaddress : " + macaddress + ",vendorCode : " + vendorCode + ",productCode :" + productCode + " , CRCresult :" + result);

        }

        @Override
        public void onGetDeviceAction(int type) throws RemoteException {
            log("onGetDeviceAction", "type:" + type);

        }


        @Override
        public void onGetBandFunction(int result, boolean[] results) throws RemoteException {
            log("onGetBandFunction", "result : " + result + ", results :" + results.length);

            String function = "";
            for (int i = 0; i < results.length; i++) {
                function += String.valueOf((i + 1) + "=" + results[i] + " ");
            }
            log("onGetBandFunction", function);
        }

        @Override
        public void onSetLanguage(int arg0) throws RemoteException {
            log("onSetLanguage", "result:" + arg0);

        }


        @Override
        public void onSendWeather(int arg0) throws RemoteException {
            log("onSendWeather", "result:" + arg0);
        }


        @Override
        public void onSetAntiLost(int arg0) throws RemoteException {
            log("onSetAntiLost", "result:" + arg0);

        }


        @Override
        public void onReceiveSensorData(int heartrate, int Systolicpressure, int Diastolicpressure, int Oxygen, int Fatiguevalue) throws RemoteException {
            log("onReceiveSensorData", "result:" + heartrate + " , " + Systolicpressure + " , " + Diastolicpressure + " , " + Oxygen + " , " + Fatiguevalue);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    nowHeartRate = String.valueOf(heartrate);
                    nowBloodOxygen = String.valueOf(Oxygen);
                    nowSystolicBloodPressure = String.valueOf(Systolicpressure);
                    nowDiastolicBloodPressure = String.valueOf(Diastolicpressure);

                    heartRate.setText(nowHeartRate);
                    bloodOxygen.setText(nowBloodOxygen);
                    bloodPressure.setText(nowSystolicBloodPressure);
                    diastolicBloodPressure.setText(nowDiastolicBloodPressure);
                }
            });
        }


        @Override
        public void onSetBloodPressureMode(int arg0) throws RemoteException {
            log("onSetBloodPressureMode", "result:" + arg0);
        }


        @Override
        public void onGetMultipleSportData(int flag, String recorddate, int mode, int value)
                throws RemoteException {

            log("onGetMultipleSportData", "flag:" + flag + " , mode :" + mode + " recorddate:" + recorddate + " , value :" + value);
        }


        @Override
        public void onSetGoalStep(int result) throws RemoteException {
            log("onSetGoalStep", "result:" + result);
        }


        @Override
        public void onSetDeviceHeartRateArea(int result) throws RemoteException {
            log("onSetDeviceHeartRateArea", "result:" + result);
        }


        @Override
        public void onSensorStateChange(int type, int state)
                throws RemoteException {

            log("onSensorStateChange", "type:" + type + " , state : " + state);
        }

        @Override
        public void onReadCurrentSportData(int mode, String time, int step,
                                           int cal) throws RemoteException {

            log("onReadCurrentSportData", "mode:" + mode + " , time : " + time + " , step : " + step + " cal :" + cal);
        }

        @Override
        public void onGetOtaInfo(boolean isUpdate, String version, String path) throws RemoteException {
            log("onGetOtaInfo", "isUpdate " + isUpdate + " version " + version + " path " + path);
        }

        @Override
        public void onGetOtaUpdate(int step, int progress) throws RemoteException {
            log("onGetOtaUpdate", "step " + step + " progress " + progress);
        }

        @Override
        public void onSetDeviceCode(int result) throws RemoteException {
            log("onSetDeviceCode", "result " + result);
        }

        @Override
        public void onGetDeviceCode(byte[] bytes) throws RemoteException {
            log("onGetDeviceCode", "bytes " + ConversionUtil.getInstance().printHexString(bytes));
        }

        @Override
        public void onCharacteristicChanged(String uuid, byte[] bytes) throws RemoteException {
//            log("onCharacteristicChanged", uuid + " " + ConversionUtil.getInstance().printHexString(bytes));
        }

        @Override
        public void onCharacteristicWrite(String uuid, byte[] bytes, int status) throws RemoteException {
            log("onCharacteristicWrite", status + " " + uuid + " " + ConversionUtil.getInstance().printHexString(bytes));
        }

        @Override
        public void onSetEcgMode(int result, int state) throws RemoteException {
            log("onSetEcgMode", "result " + result + " state " + state);
        }

        @Override
        public void onGetEcgValue(int state, int[] values) throws RemoteException {
            log("onGetEcgValue", "state " + state + " value " + values.length);

        }

        @Override
        public void onGetEcgHistory(long timestamp, int number) throws RemoteException {
            log("onGetEcgHistory", "timestamp " + timestamp + " number " + number);

        }

        @Override
        public void onGetEcgStartEnd(int id, int state, long timestamp) throws RemoteException {
            log("onGetEcgStartEnd", "id " + id + " state " + state + " timestamp " + timestamp);

        }

        @Override
        public void onGetEcgHistoryData(int id, int[] values) throws RemoteException {
            log("onGetEcgHistoryData", "id " + id + " values " + values.length);

        }

        @Override
        public void onSetDeviceName(int result) throws RemoteException {
            log("onSetDeviceName", "result " + result);
        }

        @Override
        public void onGetDeviceRssi(int rssi) throws RemoteException {
            log("onGetDeviceRssi", "rssi " + rssi);
            /*if (rssi < -75) {
                mService.disconnectBt(true);
                String name = studentsName.getText().toString();
                if (!name.isEmpty()){
                    String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    listBeans.remove(0);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("itemName", name);
                    map.put("itemStep", nowStep);
                    map.put("itemTemp", nowBodyTemp);
                    map.put("itemTime", time.split(" ")[1]);
                    listBeans.add(map);
                    mScanBleHandler.sendEmptyMessage(456);
                    mSQLiteManage.addData(nowDeviceId, name, nowMaxTemp, nowBodyTemp, nowSkinTemp,
                            nowStep, nowCalories, nowDistance, nowHeartRate, nowSystolicBloodPressure,
                            nowDiastolicBloodPressure, nowBloodOxygen, time);
                }

                oldRssi = -85;
                nowDeviceId = "";
                nowMaxTemp = "";
                nowBodyTemp = "";
                nowSkinTemp = "";
                nowStep = "";
                nowCalories = "";
                nowDistance = "";
                nowHeartRate = "";
                nowSystolicBloodPressure = "";
                nowDiastolicBloodPressure = "";
                nowBloodOxygen = "";
                runOnUiThread(() -> {
                    studentsName.setText("");
                    studentsId.setText("");
                    maxTempV.setText(nowMaxTemp);
                    bodyTempV.setText(nowBodyTemp);
                    surfaceTempV.setText(nowSkinTemp);
                    heartRate.setText(nowHeartRate);
                    bloodOxygen.setText(nowBloodOxygen);
                    bloodPressure.setText(nowSystolicBloodPressure);
                    diastolicBloodPressure.setText(nowDiastolicBloodPressure);
                    stepV.setText(nowStep);
                    kilometreV.setText(nowDistance);
                    calorieV.setText(nowCalories);
                    nowConnect.setText(nowDeviceId);
                });
                scanDevice();
            }*/
        }

        @Override
        public void onSetReminder(int result) throws RemoteException {
            log("onSetReminder", "result " + result);

        }

        @Override
        public void onSetReminderText(int result) throws RemoteException {
            log("onSetReminderText", "result " + result);

        }

        @Override
        public void onSetBPAdjust(int result) throws RemoteException {
            log("onSetBPAdjust", "result " + result);

        }

        @Override
        public void onSetTemperatureMode(int result) throws RemoteException {
            log("onSetTemperatureMode", "result " + result);

        }

        @Override
        public void onGetTemperatureData(int surfaceTemp, int bodyTemp) throws RemoteException {
            log("onGetTemperatureData", "surfaceTemp " + surfaceTemp + ", bodyTemp" + bodyTemp);
            if (update) return;
            nowBodyTemp = String.valueOf(bodyTemp).substring(0, 2) + "." + String.valueOf(bodyTemp).substring(2);
            nowSkinTemp = String.valueOf(surfaceTemp).substring(0, 2) + "." + String.valueOf(surfaceTemp).substring(2);
            if (nowMaxTemp.isEmpty()) nowMaxTemp = nowBodyTemp;
            else
                nowMaxTemp = nowMaxTemp.compareTo(nowBodyTemp) > 0 ? nowMaxTemp : nowBodyTemp;
            runOnUiThread(() -> {
                maxTempV.setText(nowMaxTemp);
                bodyTempV.setText(nowBodyTemp);
                surfaceTempV.setText(nowSkinTemp);
            });

            if (ok && stopCollection){
                ok = false;
                isSave = false;
                String name = studentsName.getText().toString();
                if (!name.isEmpty()){
//                    String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    Date date = new Date(System.currentTimeMillis());
                    String time = simpleDateFormat.format(date);
                    if (listBeans.size() > 9) listBeans.remove(0);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("itemName", name);
                    map.put("itemStep", nowStep);
                    map.put("itemTemp", nowBodyTemp);
                    map.put("itemTime", time.split(" ")[1]);
                    listBeans.add(map);
                    mScanBleHandler.sendEmptyMessage(456);
                    isSave = true;
                    mSQLiteManage.addData(nowDeviceId, name, nowMaxTemp, nowBodyTemp, nowSkinTemp,
                            nowStep, nowCalories, nowDistance, nowHeartRate, nowSystolicBloodPressure,
                            nowDiastolicBloodPressure, nowBloodOxygen, time);
                }
                if (bleArrayList.size() != 0 && num >= bleArrayList.size()){
                    stop = true;

                    if (num < Integer.parseInt(classNumber.getText().toString().trim())){
                        startCollection.setText("重新采集");
                        mScanBleHandler.sendEmptyMessage(770);
                    } else {
                        startCollection.setText("开始采集");
                        mScanBleHandler.sendEmptyMessage(771);
                    }
                }

                if (num < bleArrayList.size()){
                    Message message = new Message();
                    message.what = 999;
                    message.obj = bleArrayList.get(num);
                    mScanBleHandler.sendMessage(message);
                }
            }
        }

        @Override
        public void onTemperatureModeChange(int enable) throws RemoteException {
            log("onTemperatureModeChange", "enable " + enable);
        }
    };

}